package com.yyw.gulimall.authserver.controller;

import com.yyw.common.constant.auth.AuthServerConstant;
import com.yyw.common.constant.common.UrlConstant;
import com.yyw.common.utils.R;
import com.yyw.common.utils.enums.ExceptionEnum;
import com.yyw.gulimall.authserver.feign.ThirdPartyFeign;
import com.yyw.gulimall.authserver.service.UserService;
import com.yyw.gulimall.authserver.vo.LoginUserVo;
import com.yyw.gulimall.authserver.vo.RegisterUserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author yyw
 * @Classname IndexController
 * @Description 登录/注册 处理器
 * @Date 2020/12/10 13:56
 */
@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IndexController {

    private final ThirdPartyFeign thirdPartyFeign;
    private final UserService userService;

    /**
     * 注册发送短信验证码
     *
     * @param phone
     * @return
     */
    @GetMapping("/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam String phone) {
        if (StringUtils.isEmpty(phone)) {
            return R.error(ExceptionEnum.BINDING_PARAMETERS.getCode(), ExceptionEnum.BINDING_PARAMETERS.getMsg());
        }
        thirdPartyFeign.sendCode(phone);
        return R.ok();
    }

    /**
     * 用户注册
     *
     * @param userVo
     * @param bindingResult
     * @param model
     * @return
     */
    @RequestMapping(value = "/register/user")
    public ModelAndView registerUser(@Valid RegisterUserVo userVo, BindingResult bindingResult, ModelAndView model) {
        return userService.registerUser(userVo, bindingResult, model);
    }

    /**
     * 用户登录
     *
     * @param model
     * @param userVo
     * @param bindingResult
     * @return
     */
    @PostMapping(value = "/login/user")
    public ModelAndView loginUser(ModelAndView model, @Valid LoginUserVo userVo, BindingResult bindingResult,
                                  HttpSession session) {
        return userService.loginUser(userVo, bindingResult, model, session);
    }

    /**
     * 跳转登录页，判断是否已经登录，否则跳转首页
     *
     * @param session
     * @return
     */
    @GetMapping({"/", "/login"})
    public String login(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.SESSION_LOGIN_USER);
        if (Objects.equals(null, attribute)) {
            return "login";
        }
        return "redirect:" + UrlConstant.PRODUCT_URL;
    }
}
